package as2.controller;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import as2.model.OrderService;
import as2.model.pojo.Order;
import as2.model.pojo.OrderStatus;

public class UpdateStatus extends HttpServlet {

	// Method to handle GET method request.
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("update status");
		Long orderId = 0L;
		OrderStatus newStatus = null;

		StringBuffer jb = new StringBuffer();
		String line = null;
		try {
			BufferedReader reader = request.getReader();
			while ((line = reader.readLine()) != null)
				jb.append(line);
		} catch (Exception e) { /* report an error */
		}
		JSONObject jsonObject;
		try {
			// System.out.println(jb.toString());
			jsonObject = new JSONObject(jb.toString());
			orderId = 0L + (int) jsonObject.get("id");
			String status = (String) jsonObject.get("status");
			if ("SHIPPED".equals(status)) {
				newStatus = OrderStatus.SHIPPED;
			} else if ("DELIVERED".equals(status)) {
				newStatus = OrderStatus.DELIVERED;
			} else {
				newStatus = OrderStatus.PROCESSING;
			}
		} catch (JSONException e) {
		}
		System.out.println("order ID: " + orderId);
		System.out.println("new status: " + newStatus);

		Order order = OrderService.getOrder(orderId);
		order.setStatus(newStatus);
		OrderService.update(order);
	}

	// Method to handle POST method request.
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
